package com.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.po.Dish;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by Administrator on 2017/4/19.
 */

public class Change {
    private static ObjectMapper mapper = new ObjectMapper();
    @SuppressWarnings("unchecked")
	public static List<Dish> json_dish(String line){
//        BufferedReader reader = new BufferedReader(new FileReader("info.json"));
//        String line = reader.readLine();
//        reader.close();
        JavaType javaType = getCollectionType(ArrayList.class, Dish.class);
        List<Dish> list = null;
        try {
            list = (List<Dish>) mapper.readValue(line, javaType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
    public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }
    public static String dish_json(Set<Dish> dishlist){
        StringWriter w = new StringWriter();
        try {
            mapper.writeValue(w,dishlist);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return w.toString();
    }

    public static Dish json_onedish(String line){
        Dish dish= null;
        try {
            dish = mapper.readValue(line, Dish.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dish;
    }
    public static String asString(Object object){
        String info="";
        try {
            info=mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return info;
    }
   
}
